var url;
var socket;
var initcammand;
var emittype;
function initSocket(url, cammandArray, type) {
	socket = io.connect(url);
	socket.on('connect', connectHandler("connectHandler"));
	socket.on(type, messageHandler("messageHandler"));
	socket.on('disconnect', disconnectHandler("disconnectHandler"));

	url = url;
	initcammand = cammandArray;
	emittype = type;
}

function connectHandler(parentId) {
	return function() {
		output(
				'<span class="connect-msg">Client has connected to the server!</span>',
				parentId);
	}
}

function messageHandler(parentId) {
	return function(data) {
		output('<span class="username-msg">' + data.cammand + ':</span> ' + JSON.stringify(data));
		message(data)
	}
}

function disconnectHandler(parentId) {
	return function() {
		output(
				'<span class="disconnect-msg">The client has disconnected!</span>',
				parentId);
	}
}

function message(data) {
	var jsonArray = initcammand;
	var cammanddata = data.cammand;
	for (var i = 0; i < jsonArray.length; i++) {
		var jsonObj = jsonArray[i];
		if (cammanddata == jsonObj.command) {
			new jsonObj.fun(data);
		}
	}
}

function sendDisconnect() {
	socket.disconnect();
}

function sendMessage(jsonObject) {
	socket.emit(emittype, jsonObject);
}

function output(message) {
	var currentTime = "<span class='time'>" + moment().format('HH:mm:ss.SSS') + "</span>";
	var element = $("<div>" + currentTime + " " + message + "</div>");
	$('#console').prepend(element);
}

$(document).keydown(function(e) {
	if (e.keyCode == 13) {
		$('#send').click();
	}
});